﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Composition;
using FinMkts.CFD.DataService;
using FinMkts.CFD.Rest;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Events;

namespace FinMkts.Client
{
    [PartCreationPolicy(CreationPolicy.NonShared)]
    [Export("MainViewModel")]
    public class MainViewModel : IMainViewModel, INotifyPropertyChanged, IPartImportsSatisfiedNotification
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly IInstrumentService _instrumentService;

        [ImportingConstructor]
        public MainViewModel(IEventAggregator eventAggregator, IInstrumentService instrumentService)
        {
            _eventAggregator = eventAggregator;
            _instrumentService = instrumentService;
        }

        private ObservableCollection<InstrumentDC> _instruments;
        public ObservableCollection<InstrumentDC> Instruments
        {
            get { return _instruments; }
            set
            {
                _instruments = value;
                NotifyPropertyChanged("Instruments");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void OnImportsSatisfied()
        {
            Instruments = null;

            _eventAggregator.GetEvent<InstrumentsReceivedEvent>().Subscribe(
                instrumentsReceived =>
                {
                    Instruments = instrumentsReceived.Instruments;
                }, 
                ThreadOption.UIThread,
                true
            );

            _instrumentService.GetAll();
        }
    }
}
